<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $token = $request->header('token');
        $response = ['code' => 999];
        if($token){
            $uInfo = DB::table('admin_user')->where('token',$token)->first();
            $token_expire = strtotime($uInfo->token_expire);
            $now_time = time();
            if($uInfo && ($now_time - $token_expire <= 1800)){
                $uid = ['LoginUid'=>$uInfo->id];
                $request->merge($uid);//合并参数,将用户ID放入请求参数中
                $response = $next($request);
                //更新token过期时间
                DB::table('admin_user')->where('token',$token)->update(['token_expire'=>date('Y-m-d H:i:s',time()+1800)]);
            }
        }
        return $response;
    }
}
